/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2023 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "can.h"
#include "dma.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"
#include <stdio.h>
/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "bsp_led.h"
#include "bsp_uart.h"
#include "user_protocol.h"
#include "stm32f407xx.h"
//#include "modbus_master.h"
#include "protocol_adapter.h"
#include "bsp_iap.h"
#include "bsp_flash.h"
#if RS485
#include "Scheme/RS485.h"
#endif  /*RS485*/
#if MODBUS
#include "modbus_master.h"
#endif  /*MODBUS*/
#if NB_IOT
#include "NB_IOT.h"
#endif /*NB_IOT*/
#if G4_CAT1
#include "G4_CAT1.h"
#endif /*4G_CAT1*/

#if LORA
#include "lora.h"
#endif
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
# define CREATE_BIN  //bootloader加载
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */
/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */


//温湿度传感器
void Temp_wet_cmd(void);//走有线发送读取指令
void Temp_wet_dataCRC(uint8_t *rx_data,uint8_t len);//数据校验
/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */

int fputc(int ch,FILE*f)// 重定向printf函数到USART3
{
    HAL_UART_Transmit(&huart3, (uint8_t *)&ch, 1, HAL_MAX_DELAY);
    return ch;
}
/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{
	  /* USER CODE BEGIN 1 */
	#ifdef CREATE_BIN
		SCB->VTOR = FLASH_BASE | 0x10000; //更新中断向量表
	#endif
	  /* USER CODE END 1 */

	  /* MCU Configuration--------------------------------------------------------*/

	  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
	  HAL_Init();

	  /* USER CODE BEGIN Init */

	  /* USER CODE END Init */

	  /* Configure the system clock */
	  SystemClock_Config();

	  /* USER CODE BEGIN SysInit */
	  //HAL_Delay(100);                                                                  //由于扩展板在满载运行的情况下，外设过多，上电
	  /* USER CODE END SysInit */

	  /* Initialize all configured peripherals */
	  MX_GPIO_Init();
	  MX_DMA_Init();
	  MX_USART2_UART_Init();
	  MX_UART4_Init();
	  MX_UART5_Init();
	  MX_USART1_UART_Init();
	  MX_TIM3_Init();//
	  MX_CAN2_Init();
	  MX_USART6_UART_Init();
	  MX_USART3_UART_Init();
	  /* USER CODE BEGIN 2 */

      HAL_TIM_Base_Start_IT(&htim3);//启动定时器3
	  protocol_num();
	  Bsp_usart_enable();
	  edge_status = EDGE_OPERATE;                                                     //边缘网关重启后初始状态为运行状�??
	  ask_adapter_ok();


	  //初始化(师姐)
		#if MODBUS_485                                                                    //初始化RS485读取modbus标志
			m485_sum_info.read_finish = 1;
		#endif /*MODBUS_485*/

		#if MODBUS_NB_IOT
			nbiot_config_init(NB_WORKMODE_NET);
			mnb_sum_info.read_finish = 0;
		#endif /*MODBUS_NB_IOT*/

	//	#if MQTT_4G_CAT1
	//		g4cat1_config_init(G4_WORKMODE_MQTT);
	//	#endif /*4G_CAT1*/



//	//初始化NB/lora
//	#if LORA
//		LoRa_configuration();//先配置loRa模块
//	#endif

//	#if NB_IOT
//		NB_configuration();//配置NB模块
//	#endif /*NB_IOT*/

	int i = 0;//计数20次循环采一次温湿度

	  while (1)
	  {
//		  if(flash_flag)//进boot
//		  {
//
//		  }

		  //EXT_IO_Process();//灯处理函数
		  //whether_reset();                            // 更新flash
//		  LED_H;
//		  HAL_Delay(LED_DELAY);
//		  LED_L;
//		  HAL_Delay(LED_DELAY);
		  //led_control();

		#if MODBUS_485
			M485_read();                               //读取各线圈寄存器信息
		#if NON_INTERRUPT_PROCESS
			  RX_Parse_Data(&m485_sum_info);              //处理接收的数�?
		#endif /*NON_INTERRUPT_PROCESS*/
		#endif /*MODBUS_485*/
		#if MODBUS_NB_IOT
			  MNB_read();                               //读取各线圈寄存器信息
		#if NON_INTERRUPT_PROCESS
			  RX_Parse_Data_MNB(&mnb_sum_info);              //处理接收的数�?
		#endif /*NON_INTERRUPT_PROCESS*/
		#endif /*MODBUS_485*/

//		#if LORA
//		LoRa_send();//测距
//		#endif
//		#if NB_IOT
//		NB_send();//振动
//		#endif
//
//
//		//10s读一次温湿度
//		#if G4_CAT1
//		i++;
//		if(i>10)
//		{
//			G4_send();
//			//Temp_wet_cmd();
//			i=0;
//		}
//		#endif
		  //浪潮
		  if(QS96_clean_flag)//计数器清0
		  {
			  QS96_clean();
		  }
		  if(QS96_getdata_flag)//读计数器的值
		  {
			  QS96_getdata();
		  }
		  if(QS96_clean_single_flag)
		  {
			  QS96_single_clean();
			  QS96_clean_single_flag = 0;
		  }
		  if(QS96_getdata_single_flag)
		  {
			  QS96_get_single_data();
			  QS96_getdata_single_flag = 0;
		  }
//		  if(QS96_send_flag)
//		  {
//			  QS96_send_flag=0;
//			  Send_Data(&huart3, (uint8_t*)lora_rx_buffer, lora_rx_len);
//		  }

		/* USER CODE END WHILE */


		/* USER CODE BEGIN 3 */
		  EXT_IO_Process();//三色灯处理函数
	  }
	  /* USER CODE END 3 */

}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};

  /** Configure the main internal regulator output voltage
  */
  __HAL_RCC_PWR_CLK_ENABLE();
  __HAL_PWR_VOLTAGESCALING_CONFIG(PWR_REGULATOR_VOLTAGE_SCALE1);

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLM = 8;
  RCC_OscInitStruct.PLL.PLLN = 168;
  RCC_OscInitStruct.PLL.PLLP = RCC_PLLP_DIV2;
  RCC_OscInitStruct.PLL.PLLQ = 4;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV4;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV2;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_5) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
void Temp_wet_cmd(void)
{
	//读取温湿度
	uint8_t data_cmd[]={0x01,0x03,0x00,0x00,0x00,0x02,0xC4,0x0B};
	Send_Data(&huart6,(uint8_t*)data_cmd,sizeof(data_cmd));
	timer_count=1;//开启计数
	while(timer_count > 0 && timer_count < 50)
	{
		if(u485_rx_flag)//收到返回的数据
		{
			u485_rx_flag = 0;//标志位清一下
			Temp_wet_dataCRC(u485_rx_buffer,u485_rx_len);//数据检查
			timer_count=0;//关计数
			break;
		}
	}
//	if(timeout_flag)
//	{
//		timeout_flag=0;
//		Send_Data(&huart3,(uint8_t*)"error",strlen("error"));//正常来说响应OK才能进行配置
//		//break;//跳出大循环
//	}
}
//温湿度数据校验
void Temp_wet_dataCRC(uint8_t *rx_data,uint8_t len)
{
	if((rx_data[0]==0x01)&&(rx_data[1]==0x03))//modbus地址01，功能码03
	{
		rx_data[0]=0x07;//数据头
	}
	Send_Data(&huart3, rx_data, len);//数据发回网关
}
/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
